package com.cstor.liang.web.controller;

import com.cstor.liang.config.ProjectSettings;
import com.cstor.liang.pojo.other.ResultJo;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2017/9/4.
 */
@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private ProjectSettings projectSettings;

    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public ResultJo upload(MultipartFile file, HttpServletRequest request) throws Exception{

        if (file == null || file.isEmpty()){
            return ResultJo.returnError(1, "未发现文件！");
        }else {
            File savedFile = null;
            //判断是否存在自定义的文件路径
            if (projectSettings.getFilePath() == null || projectSettings.getFilePath().equals("")){
                savedFile = new File(request.getSession().getServletContext().getRealPath("/") +
                                ProjectSettings.FILE_PATH + file.getOriginalFilename());
            }else{
                //判断路径是否末尾接文件分隔符
                if (!projectSettings.getFilePath().endsWith(File.separator))
                    savedFile = new File(projectSettings.getFilePath() + "/" + file.getOriginalFilename());
                else
                    savedFile = new File(projectSettings.getFilePath() + file.getOriginalFilename());
            }

            //判断目标文件所在的目录是否存在
            if(!savedFile.getParentFile().exists())
                if(!savedFile.getParentFile().mkdirs())
                    throw new RuntimeException("创建目标文件所在目录失败！");

            //开始存储文件
            file.transferTo(savedFile);

            //未抛出错误，执行成功
            return ResultJo.returnOk(null);
        }
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download(String fileName, HttpServletRequest request) throws IOException {
        //数据校验
        if (fileName == null){
            //校验失败，收集所有错误
            throw new RuntimeException("缺少fileName");
        }

        File savedFile = null;
        //判断是否存在自定义的文件路径
        if (projectSettings.getFilePath() == null || projectSettings.getFilePath().equals("")){
            savedFile = new File(request.getSession().getServletContext().getRealPath("/") +
                    ProjectSettings.FILE_PATH + fileName);
        }else{
            //判断路径是否末尾接文件分隔符
            if (!projectSettings.getFilePath().endsWith(File.separator))
                savedFile = new File(projectSettings.getFilePath() + "/" + fileName);
            else
                savedFile = new File(projectSettings.getFilePath() + fileName);
        }
        //查看文件是否存在
        if (!savedFile.exists())
            throw new RuntimeException("文件不存在");
        //设置头部
        HttpHeaders headers = new HttpHeaders();
//        //为了解决中文名称乱码问题
//        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(savedFile),
                headers, HttpStatus.CREATED);
    }
}
